package com.hsgene.common.util.qiniu;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.hsgene.common.util.character.CharactersConstant;
import com.hsgene.common.util.result.ApiResult;
import com.qiniu.util.Auth;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import java.util.Collection;
import java.util.LinkedList;
import java.util.List;

/**
 * @author wxf
 * @date 2018/11/23 13:54
 **/
public class QiniuCertificateUtil {

    /**
     * LOG
     */
    private static Logger LOGGER = LogManager.getLogger(QiniuCertificateUtil.class);
    /**
     * 访问秘钥
     */
    private static String accessKey = "G56SPDFY9BQm4u6bbhigTwVptUUqywG78BuyWpmf";
    /**
     * 加密秘钥
     */
    private static String secretKey = "BKQKJkTAmXPX4Camr7dEPZ6WdMiruz-ztHLsLd5Y";

    /**
     * 获取下载凭证
     *
     * @param data
     * @return
     */
    //TODO 待取消
    public static Object getDownloadCertificate(Object data) {
        try {
            if (data == null) {
                LOGGER.warn("qiniu imageUrls is not null");
                return new ApiResult<>(-1, "failed", "图片地址不能为空", null);
            }
            Auth auth = Auth.create(accessKey, secretKey);
            if (data instanceof String) {
                String signTokens = auth.privateDownloadUrl(String.valueOf(data));
                LOGGER.info("one qiniu certificate is :" + signTokens);
                return signTokens;
            }
            if (data instanceof List) {
                List<String> signTokens = new LinkedList<>();
                List<String> params = (List<String>) data;
                params.stream().forEach(imageUrl -> {
                    String signToken = auth.privateDownloadUrl(imageUrl);
                    signTokens.add(signToken);
                });
                LOGGER.info("many qiniu certificate is :" + signTokens);
                return signTokens;
            }
            return data;
        } catch (Exception e) {
            LOGGER.error("获取下载凭证异常", e);
            return null;
        }
    }

    /**
     * 多个字符串
     *
     * @param data
     * @return
     */
    public static String getDownloadCertificateStr(String data) {
        try {
            if (data == null) {
                LOGGER.warn("qiniu imageUrls is not null");
                return null;
            }
            StringBuffer buffer = new StringBuffer();
            //包含英文逗号,说明有多个
            //json数组
            if (data.contains("[")) {
                JSONArray json = JSON.parseArray(data);
                for (int i = 0; i < json.size() - 1; i++) {
                    buffer.append(getOneDownloadCertificate(String.valueOf(json.get(i)))).append(CharactersConstant
                            .COMMA_EN);
                }
                buffer.append(getOneDownloadCertificate(String.valueOf(json.get(json.size() - 1))));
            } else {
                String[] array = data.split(CharactersConstant.COMMA_EN);
                for (int i = 0; i < array.length - 1; i++) {
                    buffer.append(getOneDownloadCertificate(array[i])).append(CharactersConstant.COMMA_EN);
                }
                buffer.append(getOneDownloadCertificate(array[array.length - 1]));
            }
            LOGGER.info("many qiniu certificate is :" + buffer.toString());
            return buffer.toString();
        } catch (Exception e) {
            LOGGER.error("获取下载凭证异常", e);
            return null;
        }
    }

    /**
     * list
     *
     * @param data
     * @return
     */
    public static List<String> getDownloadCertificateList(List<String> data) {
        if (data == null || data.isEmpty()) {
            LOGGER.warn("qiniu imageUrls is not null");
            return null;
        }
        List<String> result = new LinkedList<>();
        data.stream().forEach(image -> {
            result.add(getOneDownloadCertificate(image));
        });
        return result;
    }

    /**
     * list
     *
     * @param data
     * @return
     */
    public static Collection<String> getDownloadCertificateCollection(Collection<String> data) {
        if (data == null || data.isEmpty()) {
            LOGGER.warn("qiniu imageUrls is not null");
            return null;
        }
        List<String> result = new LinkedList<>();
        data.stream().forEach(image -> {
            result.add(getOneDownloadCertificate(image));
        });
        return result;
    }

    /**
     * 获取下载凭证
     *
     * @param data
     * @return
     */
    public static String getOneDownloadCertificate(String data) {
        try {
            if (data == null) {
                LOGGER.warn("qiniu imageUrls is not null");
                return null;
            }
            LOGGER.info("get image url is :" + data);
            Auth auth = Auth.create(accessKey, secretKey);
            String signTokens = auth.privateDownloadUrl(data.split("\\?")[0]);
            LOGGER.info("one qiniu certificate is :" + signTokens);
            return signTokens;
        } catch (Exception e) {
            LOGGER.error("获取下载凭证异常", e);
            return null;
        }
    }
}
